<?php
class Module {
    private $name;
    private $dir;
    
    
    public function init() {}
    
    
    public function set_name($name) {
        $this->name = $name;
    }
    
    
    public function set_dir($dir) {
        $this->dir = $dir;
    }
    
    
    public function model($name) {
        static $models = array();
        
        if ( ! isset($models[$name])) {
            $file = $this->dir . "/model/$name.php";
            if ( ! file_exists($file)) {
                tos_die("$file does not exists!");
            }
            
            include_once $file;
            
            $class_name = ucfirst($this->name . '_model_' . $name);
            
            if ( ! class_exists($class_name)) {
                tos_die("class $class_name does not exists");
            }
            
            $model = new $class_name();
            $model->set_module($this->name);
            $model->init();
            
            $models[$name] = $model;
        }
        
        return $models[$name];
    }
    
    
    public function view($name, $data = array()) {
        static $views = array();
        
        if ( ! isset($views[$name])) {
            $file = $this->dir . "/view/$name.php";
            if (file_exists($file)) {
                $class_name = ucfirst($this->name . '_view_' . $name);
                if ( ! class_exists($class_name)) {
                    tos_die("View class $class_name does not exists!");
                }
                $view = new $class_name($name);
            } else {
                $view = new View($name);
            }
            
            $views[$name] = $view;
        }
        
        if ($data) {
            $views[$name]->merge_data($data);
        }
        return $views[$name];
    }
    
}
?>